<template>
  <div class="role-manage">
    <h2>角色管理</h2>
    <el-table :data="roles.records" style="width: 100%" border>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="nameZh" label="角色中文名称" align="center"></el-table-column>
      <el-table-column prop="name" label="角色英文名称" align="center"></el-table-column>
      <el-table-column label="初始属性" align="center">
        <template #default="scope">
          <span v-if="scope.row.initialAttributes">
            {{ parseInitialAttributes(scope.row.initialAttributes) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="backgroundInfo" label="背景信息" align="center"></el-table-column>
      <el-table-column label="装备" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEquipments(scope.row)">查看装备</el-button>
        </template>
      </el-table-column>
      <el-table-column label="任务" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showRoleTasks(scope.row)">查看任务</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="roles.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="roles.rows"
          layout="total, sizes, prev, pager, next, jumper"
          :total="roles.total"
      ></el-pagination>
    </div>

    <el-button type="primary" @click="showAddRoleDialog">新增角色</el-button>

    <!-- 新增角色对话框 -->
    <el-dialog title="新增角色" v-model="addRoleDialogVisible" width="30%">
      <el-form :model="newRole">
        <el-form-item label="角色中文名称">
          <el-input v-model="newRole.nameZh"></el-input>
        </el-form-item>
        <el-form-item label="角色英文名称">
          <el-input v-model="newRole.name"></el-input>
        </el-form-item>
        <el-form-item label="初始属性">
          <el-input type="textarea" v-model="newRole.initialAttributes"></el-input>
        </el-form-item>
        <el-form-item label="背景信息">
          <el-input type="textarea" v-model="newRole.backgroundInfo"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" v-model="editRoleDialogVisible" width="30%">
      <el-form :model="currentRole">
        <el-form-item label="角色中文名称">
          <el-input v-model="currentRole.nameZh"></el-input>
        </el-form-item>
        <el-form-item label="角色英文名称">
          <el-input v-model="currentRole.name"></el-input>
        </el-form-item>
        <el-form-item label="初始属性">
          <el-input type="textarea" v-model="currentRole.initialAttributes"></el-input>
        </el-form-item>
        <el-form-item label="背景信息">
          <el-input type="textarea" v-model="currentRole.backgroundInfo"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateRole">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色装备管理对话框 -->
    <el-dialog title="角色装备管理" v-model="equipmentsDialogVisible" width="60%">
      <div class="role-equipments">
        <h3>{{ currentRoleForEquipments.nameZh || '未选择角色' }} 的装备</h3>

        <el-row>
          <el-col :span="12">
            <h4>已装备</h4>
            <el-table :data="currentRoleEquipments" style="width: 100%" border>
              <el-table-column prop="id" label="装备ID" align="center"></el-table-column>
              <el-table-column prop="name" label="装备名称" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button
                      size="mini"
                      type="danger"
                      @click="removeEquipment(currentRoleForEquipments.id, scope.row.id)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <el-col :span="12">
            <h4>可用装备</h4>
            <el-input
                v-model="equipmentSearchKey"
                placeholder="搜索装备名称"
                clearable
                @clear="loadAvailableEquipments"
                @keyup.enter.native="loadAvailableEquipments">
              <template #append>
                <el-button @click="loadAvailableEquipments">搜索</el-button>
              </template>
            </el-input>

            <el-table :data="availableEquipments" style="width: 100%" border>
              <el-table-column prop="id" label="装备ID" align="center"></el-table-column>
              <el-table-column prop="name" label="装备名称" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button
                      size="mini"
                      type="primary"
                      @click="addEquipment(currentRoleForEquipments.id, scope.row.id)">
                    添加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="equipmentsDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色任务对话框 -->
    <el-dialog title="角色任务" v-model="roleTasksDialogVisible" width="50%">
      <el-table :data="roleTasks" style="width: 100%" border>
        <el-table-column prop="id" label="任务ID" align="center"></el-table-column>
        <el-table-column prop="name" label="任务名称" align="center"></el-table-column>
        <el-table-column prop="description" label="任务描述" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.completed? 'success':'warning'">
              {{ scope.row.completed? '已完成' : '未完成' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleTasksDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

// 修改数据结构，适配后端分页响应
const roles = ref({
  page: 1,      // 当前页码
  rows: 10,     // 每页条数
  total: 0,     // 总记录数
  records: []   // 角色数据列表
});
const newRole = ref({ nameZh: '', name: '', initialAttributes: '', backgroundInfo: '' });
const currentRole = ref({ nameZh: '', name: '', initialAttributes: '', backgroundInfo: '' });
const addRoleDialogVisible = ref(false);
const editRoleDialogVisible = ref(false);

// 装备管理相关状态
const equipmentsDialogVisible = ref(false);
const currentRoleForEquipments = ref({});
const currentRoleEquipments = ref([]);
const availableEquipments = ref([]);
const equipmentSearchKey = ref('');

// 任务管理相关状态
const roleTasks = ref([]);
const roleTasksDialogVisible = ref(false);
const currentRoleForTasks = ref({});

// 获取角色列表（带分页）
const getRoles = async (page = 1, pageSize = 10) => {
  try {
    const res = await request.get('/roles', {
      params: {
        page,
        pageSize
      }
    });
    if (res.code === 200) {
      // 确保数据结构正确
      roles.value = {
        page: res.data.page || 1,
        rows: res.data.rows || 10,
        total: res.data.total || 0,
        records: Array.isArray(res.data.records) ? res.data.records : []
      };
    } else {
      ElMessage.error(res.message || '获取角色列表失败');
    }
  } catch (error) {
    console.error('获取角色列表出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

onMounted(() => {
  getRoles(); // 初始化加载第一页数据
});

// 分页事件处理
const handleSizeChange = (newSize) => {
  getRoles(1, newSize); // 切换每页数量时，重置到第一页
};

const handleCurrentChange = (newPage) => {
  getRoles(newPage, roles.value.rows);
};

// 新增角色相关逻辑
const showAddRoleDialog = () => {
  addRoleDialogVisible.value = true;
};

const addRole = async () => {
  try {
    const res = await request.post('/role', newRole.value);
    if (res.code === 200) {
      ElMessage.success("新增角色成功");
      await getRoles();
      addRoleDialogVisible.value = false;
      newRole.value = { nameZh: '', name: '', initialAttributes: '', backgroundInfo: '' };
    } else {
      ElMessage.error(res.message || '新增角色失败');
    }
  } catch (error) {
    console.error('新增角色出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 编辑角色相关逻辑
const handleEdit = (row) => {
  currentRole.value = { ...row };
  editRoleDialogVisible.value = true;
};

const updateRole = async () => {
  try {
    const res = await request.put('/role', currentRole.value);
    if (res.code === 200) {
      ElMessage.success("更新角色成功");
      await getRoles();
      editRoleDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || '更新角色失败');
    }
  } catch (error) {
    console.error('更新角色出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 删除角色相关逻辑
const handleDelete = async (row) => {
  if (confirm(`确定要删除角色 ${row.nameZh} 吗？`)) {
    try {
      const res = await request.delete(`/role/${row.id}`);
      if (res.code === 200) {
        ElMessage.success("删除角色成功");
        await getRoles();
      } else {
        ElMessage.error(res.message || '删除角色失败');
      }
    } catch (error) {
      console.error('删除角色出错:', error);
      ElMessage.error('网络请求失败，请检查控制台日志');
    }
  }
};

// 解析 initialAttributes 字段
const parseInitialAttributes = (initialAttributes) => {
  try {
    const parsed = JSON.parse(initialAttributes);
    return JSON.stringify(parsed, null, 2); // 格式化输出
  } catch (e) {
    return initialAttributes; // 如果解析失败，返回原始字符串
  }
};

// 装备管理相关逻辑
const showEquipments = async (role) => {
  currentRoleForEquipments.value = { ...role };
  await loadRoleEquipments(role.id);
  await loadAvailableEquipments();
  equipmentsDialogVisible.value = true;
};

// 获取角色的所有装备
const loadRoleEquipments = async (roleId) => {
  try {
    const res = await request.get(`/role/${roleId}/equipments`);
    if (res.code === 200) {
      // 确保返回数据是数组
      currentRoleEquipments.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error(res.message || '获取角色装备失败');
      currentRoleEquipments.value = [];
    }
  } catch (error) {
    console.error('获取角色装备出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
    currentRoleEquipments.value = [];
  }
};

// 加载可用装备列表
const loadAvailableEquipments = async () => {
  try {
    // 假设这里有一个接口可以获取可用装备列表，实际项目中需要根据后端接口调整
    let url = '/equipments';
    if (equipmentSearchKey.value) {
      url += `?search=${encodeURIComponent(equipmentSearchKey.value)}`;
    }

    const res = await request.get(url);
    if (res.code === 200) {
      // 关键修复：确保res.data是数组后再使用filter
      if (Array.isArray(res.data)) {
        const equippedIds = currentRoleEquipments.value.map(e => e.id);
        availableEquipments.value = res.data.filter(e => !equippedIds.includes(e.id));
      } else {
        console.error('后端返回的数据格式错误，不是数组:', res.data);
        ElMessage.error('获取可用装备列表失败：数据格式错误');
        availableEquipments.value = [];
      }
    } else {
      ElMessage.error(res.message || '获取可用装备失败');
      availableEquipments.value = [];
    }
  } catch (error) {
    console.error('获取可用装备出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
    availableEquipments.value = [];
  }
};

// 添加装备到角色
const addEquipment = async (roleId, equipmentId) => {
  try {
    const res = await request.post(`/role/${roleId}/equipment/${equipmentId}`);
    if (res.code === 200) {
      ElMessage.success("添加装备成功");
      await loadRoleEquipments(roleId);
      await loadAvailableEquipments();
    } else {
      ElMessage.error(res.message || '添加装备失败');
    }
  } catch (error) {
    console.error('添加装备出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 从角色移除装备
const removeEquipment = async (roleId, equipmentId) => {
  try {
    const res = await request.delete(`/role/${roleId}/equipment/${equipmentId}`);
    if (res.code === 200) {
      ElMessage.success("移除装备成功");
      await loadRoleEquipments(roleId);
      await loadAvailableEquipments();
    } else {
      ElMessage.error(res.message || '移除装备失败');
    }
  } catch (error) {
    console.error('移除装备出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 任务管理相关逻辑
const showRoleTasks = async (role) => {
  currentRoleForTasks.value = { ...role };
  await loadRoleTasks(role.id);
  roleTasksDialogVisible.value = true;
};

const loadRoleTasks = async (roleId) => {
  try {
    const res = await request.get(`/role/${roleId}/tasks`);
    if (res.code === 200) {
      // 确保返回数据是数组
      roleTasks.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error(res.message || '获取角色任务失败');
      roleTasks.value = [];
    }
  } catch (error) {
    console.error('获取角色任务出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
    roleTasks.value = [];
  }
};
</script>

<style scoped>
.role-equipments h3 {
  margin-bottom: 20px;
}

.role-equipments h4 {
  margin-bottom: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
}
</style>